﻿using System;
using System.Collections.Generic;
using System.IO;

namespace MetaMapics.Pbf.Indexed
{
  public class NumericIndexedPbfWriter<T> : IDisposable where T : IPbfStreamable
  {
    private string filePath;
    private Stream stream;
    private PbfWriter writer;
    private SortedList<long, long> index;

    public NumericIndexedPbfWriter(string filePath)
    {
      this.filePath = filePath;
      stream = File.Create(filePath);
      writer = new PbfWriter(stream);
      index = new SortedList<long, long>();
    }

    public void Add(long key, T pbfRecord)
    {
      index.Add(key, stream.Position);
      writer.WriteNestedMessage(1, pbfRecord);
    }

    public void WriteIndex()
    {
      string indexFilePath = filePath.Substring(0, filePath.LastIndexOf('.')) + ".pbx";
      using (var stream = File.Create(indexFilePath))
      using (var writer = new PbfWriter(stream))
      {
        writer.Write(1,index.Count);
        writer.WritePacked(2, index.Keys, PbfFieldType.Sfixed64);
        writer.WritePacked(3, index.Values, PbfFieldType.Sfixed64);
      }
    }

    public void Close()
    {
      Dispose();
    }

    public void Dispose()
    {
      writer.Close();
      stream.Close();
    }
  }
}
